package dao;

import bean.ChatGroup;
import bean.Message;
import bean.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import utils.JDBCUtils;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

public class MessageDao {
    public Deque<String> lastList = new ArrayDeque<>();

    /**
     * 发送（新建）一条消息
     * @param newMessage
     * @return
     */
    public boolean sendMessage(Message newMessage) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
// 获取数据库连接
            conn = JDBCUtils.getConnection();
// 根据sql 模板创建对应的预编译对象并将传入的形参赋值模板，替换掉sql 模板中“？”
            String sql = "insert into chat.message(toId, fromId, sendTime, content, type, isRead) values (?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            BigDecimal now = new BigDecimal(df.format(new Date()));
            pstmt.setString(1, newMessage.getToId());
            pstmt.setString(2, newMessage.getFromId());
            pstmt.setBigDecimal(3, now);
            pstmt.setString(4, newMessage.getContent());
            pstmt.setString(5, newMessage.getType());
            pstmt.setString(6, "0");
            if (lastList.size()>5){
                lastList.pop();
            }
            lastList.push(newMessage.getContent());

// 执行插入数据操作
            int num = pstmt.executeUpdate();
            if (num > 0) {
                return true;
            }
        } catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block

            e.printStackTrace();
        } finally {
            try {
                JDBCUtils.release(pstmt, conn);
            } catch (SQLException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 列出私聊所有消息
     * @param userId
     * @param toId
     * @return
     */
    public ArrayList<Message> listAllPersonalMassage(String userId, String toId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        ArrayList<Message> list = new ArrayList<>();
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select * from chat.message where fromId = "+ userId +" and toId =  "+ toId+ "  and type = 0 order by sendTime DESC ";

            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
//            System.out.println(rs.next());
            while (rs.next()){
//                System.out.println(rs.getInt("messageId"));
                   int messageId =  rs.getInt("messageId");
                   String newToId = rs.getString("toId");
                   String newFromId = rs.getString("fromId");
                   BigDecimal sendTime = rs.getBigDecimal("sendTime");
                   String content = rs.getString("content");
                   String type = rs.getString("type");
                   String isRead = rs.getString("isRead");
                   long newSendTime = sendTime.longValue();
                   Message message = new Message(messageId,newToId,newFromId,newSendTime,content,isRead,type);
                   list.add(message);
            }
//            lastList.push(list.get(0));
//            lastList.push(list.get(1));
//            lastList.push(list.get(3));
            String sql1 = "select * from chat.message where fromId ="+ toId +" and toId = "+ userId+" and type = 0 order by sendTime DESC ";
            pstmt = conn.prepareStatement(sql1);
            rs = pstmt.executeQuery();
//            System.out.println(rs.next());
            while (rs.next()){
//                System.out.println(rs.getInt("messageId"));
                int messageId =  rs.getInt("messageId");
                String newToId = rs.getString("toId");
                String newFromId = rs.getString("fromId");
                BigDecimal sendTime = rs.getBigDecimal("sendTime");
                String content = rs.getString("content");
                String type = rs.getString("type");
                String isRead = rs.getString("isRead");
                long newSendTime = sendTime.longValue();
                Message message = new Message(messageId,newToId,newFromId,newSendTime,content,isRead,type);
                list.add(message);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 列出所有群消息
     * @param group
     * @return
     */
    public ArrayList<Message> listAllChatGroupMassage(ChatGroup group){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        ArrayList<Message> list = new ArrayList<>();
        Message message = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select * from chat.message where type="  + group.getChatGroupId() ;

            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()){
                message = new Message("1",rs.getString("fromId"));
                message.setContent(rs.getString("content"));
                message.setSendTime(Long.parseLong(rs.getString("sendTime")));
                message.setMessageId(Integer.parseInt(rs.getString("messageId")));
                list.add(message);
            }
//            lastList.push(list.get(0));
//            lastList.push(list.get(1));
//            lastList.push(list.get(3));


        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

        return list;
    }




}
